package com.duowan.cms.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import com.duowan.cms.common.exception.BaseCheckedException;

/**
 * HTTP请求工具
 * 
 * @author coolcooldee
 */
public abstract class NetUtil {

    private static Log logger = LogFactory.getLog(NetUtil.class);
    private static final String EXCEPTION_BASE_KEY = NetUtil.class.getName();
    public static final String EXCEPTION_KEY_SERVER_ERROR = EXCEPTION_BASE_KEY.concat(".ServerError");

    /**
     * 异常码：签名不正确
     */
    public static final String ERROR_INVALID_SIGN = "90";
    /**
     * 异常码：服务不可用
     */
    public static final String ERROR_SERVICE_UNAVAILABLE = "91";
    /**
     * 异常码：无效请求
     */
    public static final String ERROR_INVALID_REQUEST = "92";
    /**
     * 异常码：服务器内部错误
     */
    public static final String ERROR_INTERNAL_SERVER_ERROR = "93";
    /**
     * 异常码：应用不存在
     */
    public static final String ERROR_APPLICATION_IS_NOT_EXISTED = "94";
    /**
     * 异常码：服务不存在
     */
    public static final String ERROR_SERVICE_IS_NOT_FOUND = "95";
    /**
     * 异常码：非法请求参数
     */
    public static final String ERROR_ILLEGAL_REQUEST_PARAMETER = "96";
    /**
     * 异常码：受限的请求者（未经允许访问，如受限IP）
     */
    public static final String ERROR_ILLEGAL_REQUEST = "97";

    /**
     * 异常信息容器
     */
    private static Map<String, String> errMsgContainer = new HashMap<String, String>();

    /**
     * 连接超时时间
     */
    private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 5 * 1000;

    /**
     * 读超时时间
     */
    private static final int DEFAULT_READ_TIMEOUT_MS = 10 * 1000;

    /**
     * 默认编码
     */
    protected static final String DEFAULT_CHARSET = "UTF-8";

    private static final HttpClient HTTP_CLIENT;
    static {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);
        HTTP_CLIENT = new DefaultHttpClient(cm);
        HTTP_CLIENT.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_MS);
        HTTP_CLIENT.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_READ_TIMEOUT_MS);
        HTTP_CLIENT.getParams().setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 16 * 1024);
        HTTP_CLIENT.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    }

    /**
     * 根据具体的的KEY来获取U点续费错误信息
     * 
     * @param key
     * @return
     */
    public static String getErrorMessageInfo(String key) {
        if (StringUtil.isEmpty(key))
            return "";
        if (errMsgContainer.isEmpty()) {
            errMsgContainer.put(ERROR_INVALID_SIGN, "签名不正确");
            errMsgContainer.put(ERROR_SERVICE_UNAVAILABLE, "服务不可用");
            errMsgContainer.put(ERROR_INVALID_REQUEST, "无效请求");
            errMsgContainer.put(ERROR_INTERNAL_SERVER_ERROR, "服务器内部错误");
            errMsgContainer.put(ERROR_APPLICATION_IS_NOT_EXISTED, "应用不存在");
            errMsgContainer.put(ERROR_SERVICE_IS_NOT_FOUND, "服务不存在");
            errMsgContainer.put(ERROR_ILLEGAL_REQUEST_PARAMETER, "非法请求参数");
            errMsgContainer.put(ERROR_ILLEGAL_REQUEST, "受限的请求者");
            errMsgContainer = Collections.unmodifiableMap(errMsgContainer);
        }
        return errMsgContainer.get(key);
    }

    /**
     * 是否包含指定的异常KEY
     * 
     * @param errMsgKey
     * @return
     */
    public static boolean isContainsTheErrMsgKey(String errMsgKey) {
        if (errMsgContainer.isEmpty())
            getErrorMessageInfo("");
        return errMsgContainer.keySet().contains(errMsgKey);
    }

    /**
     * 发送POST请求
     * 
     * @param paramStr 字符串形式的参数
     * @param postUrl POST请求的URL
     * @param expireSeconds 请求超时时间，单位为秒
     * @throws BaseCheckedException
     */
    public static String postHttpRequest(String paramStr, String postUri, int expireSeconds) throws BaseCheckedException {
        return postHttpRequest(paramStr, postUri, expireSeconds, DEFAULT_CHARSET);
    }

    /**
     * 发送GET请求
     * 
     * @param paramStr 字符串形式的参数
     * @param getUrl GET请求的URL
     * @param expireSeconds 请求超时时间，单位为秒
     * @throws BaseCheckedException
     */
    public static String getHttpRequest(String paramStr, String getUri, int expireSeconds) throws BaseCheckedException {
        return getHttpRequest(paramStr, getUri, expireSeconds, DEFAULT_CHARSET);
    }

    /**
     * 发送POST请求
     * 
     * @param paramStr 字符串形式的参数
     * @param postUrl POST请求的URL
     * @param expireSeconds 请求超时时间，单位为秒
     * @param charSet 字符集
     * @throws BaseCheckedException
     */
    public static String postHttpRequest(String paramStr, String postUrl, int expireSeconds, String charSet) throws BaseCheckedException {
        if (paramStr == null)
            paramStr = "";
        return postHttpRequest(UrlUtil.convertUrlParameterStringToMap(paramStr), postUrl, expireSeconds, charSet);
    }

    /**
     * 发送GET请求
     * 
     * @param paramStr 字符串形式的参数
     * @param getUrl GET请求的URL
     * @param expireSeconds 请求超时时间，单位为秒]
     * @param charSet 字符集
     * @throws BaseCheckedException
     */
    public static String getHttpRequest(String paramStr, String getUrl, int expireSeconds, String charSet) throws BaseCheckedException {
        if (paramStr == null)
            paramStr = "";
        return getHttpRequest(UrlUtil.convertUrlParameterStringToMap(paramStr), getUrl, expireSeconds, charSet);
    }

    /**
     * 发送POST请求
     * 
     * @param uParamsMap Map形式的参数
     * @param postUrl POST请求的URL
     * @param expireSeconds 请求超时时间，单位为秒
     * @throws BaseCheckedException
     */
    public static String postHttpRequest(Map<String, String> uParamsMap, String postUri, int expireSeconds) throws BaseCheckedException {
        return postHttpRequest(uParamsMap, postUri, expireSeconds, DEFAULT_CHARSET);
    }

    /**
     * 发送POST请求
     * 
     * @param uParamsMap Map形式的参数
     * @param getUrl GET请求的URL
     * @param expireSeconds 请求超时时间，单位为秒
     * @throws BaseCheckedException
     */
    public static String getHttpRequest(Map<String, String> uParamsMap, String getUri, int expireSeconds) throws BaseCheckedException {
        return getHttpRequest(uParamsMap, getUri, expireSeconds, DEFAULT_CHARSET);
    }

    /**
     * 发送POST请求
     * 
     * @param uParamsMap Map形式的�数
     * @param postUrl POST请求的URL
     * @param expireSeconds 请求超时时间，单位为秒
     * @param charSet 字符集
     * @throws BaseCheckedException
     */
    public static String postHttpRequest(Map<String, String> uParamsMap, String postUrl, int expireSeconds, String charSet) throws BaseCheckedException {
        logger.debug("以HTTP Client的方式，发送POST请求.");
        NameValuePair[] nameValuPairArray = convertParamsMap2NameValuePair(uParamsMap);
        HttpPost postMethod = new HttpPost(postUrl);
        StringEntity postEntity = null;
        List<NameValuePair> parameters = Arrays.asList(nameValuPairArray);
        try {
            postEntity = new UrlEncodedFormEntity(parameters, charSet);
        } catch (UnsupportedEncodingException e) {
            try {
                postEntity = new UrlEncodedFormEntity(parameters);
            } catch (UnsupportedEncodingException e1) {
                // should not happend, default charset is ISO_8859_1
                return null;
            }
        }
        postMethod.setEntity(postEntity);
        String result = httpRequest(postMethod, expireSeconds, postUrl, charSet);
        logger.debug("POST请求发送完毕. ");
        return result;
    }

    /**
     * 发送POST请求
     * 
     * @param uParamsMap Map形式的参数
     * @param getUrl GET请求的URL
     * @param expireSeconds 请求超时时间，单位为秒
     * @param charSet 字符集
     * @throws BaseCheckedException
     */
    public static String getHttpRequest(Map<String, String> uParamsMap, String getUrl, int expireSeconds, String charSet) throws BaseCheckedException {
        logger.debug("以HTTP Client的方式，发送GET请求.");
        String queryString = formUrlEncode(convertParamsMap2NameValuePair(uParamsMap), charSet);
        HttpGet getMethod = null;
        if (StringUtil.isEmpty(queryString)) {
            getMethod = new HttpGet(getUrl);
        } else {
            getMethod = new HttpGet(getUrl + "?" + queryString);
        }
        String result = httpRequest(getMethod, expireSeconds, getUrl, charSet);
        logger.debug("GET请求发送完毕. ");
        return result;
    }

    protected static String formUrlEncode(NameValuePair[] pairs, String charset) {
        try {
            return doFormUrlEncode(pairs, charset);
        } catch (UnsupportedEncodingException e) {
            try {
                return doFormUrlEncode(pairs, DEFAULT_CHARSET);
            } catch (UnsupportedEncodingException fatal) {
                // Should never happen. ISO-8859-1 must be supported on all JVMs
                return null;
            }
        }
    }

    protected static String doFormUrlEncode(NameValuePair[] pairs, String charset) throws UnsupportedEncodingException {
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < pairs.length; i++) {
            URLCodec codec = new URLCodec();
            NameValuePair pair = pairs[i];
            if (pair.getName() != null) {
                if (i > 0) {
                    buf.append("&");
                }
                buf.append(codec.encode(pair.getName(), charset));
                buf.append("=");
                if (pair.getValue() != null) {
                    buf.append(codec.encode(pair.getValue(), charset));
                }
            }
        }
        return buf.toString();
    }

    /**
     * 转换Map的参数成NameValuePair
     * 
     * @param uParamsMap
     * @return
     */
    public static NameValuePair[] convertParamsMap2NameValuePair(Map<String, String> uParamsMap) {
        if (uParamsMap == null)
            uParamsMap = new HashMap<String, String>();
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : uParamsMap.entrySet()) {
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        NameValuePair[] nameValuPairArray = nameValuePairs.toArray(new NameValuePair[nameValuePairs.size()]);
        return nameValuPairArray;
    }

    /**
     * 发送POST请求
     * 
     * @param postMethods HttpMethodBase对象
     * @param expireSeconds 请求超时时间，单位为秒
     * @throws BaseCheckedException
     */
    public static String httpRequest(HttpEntityEnclosingRequestBase postMethod, int expireSeconds, String requestUri) throws BaseCheckedException {
        return httpRequest(postMethod, expireSeconds, requestUri, null);
    }

    /**
     * 发送POST请求
     * 
     * @param postMethods HttpMethodBase对象
     * @param expireSeconds 请求超时时间，单位为秒
     * @param charSet 字符集
     * @throws BaseCheckedException
     */
    public static String httpRequest(HttpRequestBase httpMethod, int expireSeconds, String requestUri, String charSet) throws BaseCheckedException {
        return httpRequest(HTTP_CLIENT, httpMethod, expireSeconds, requestUri, charSet);
    }

    /**
     * 对比 httpRequest ，增多HttpClient参数，方便子类扩展
     * 
     * @param httpClient
     * @param httpMethod
     * @param expireSeconds
     * @param requestUri
     * @param charSet
     * @return
     * @throws BaseCheckedException
     */
    protected static String httpRequest(HttpClient httpClient, HttpRequestBase httpMethod, int expireSeconds, String requestUri, String charSet) throws BaseCheckedException {
        if (expireSeconds > 0) {
            httpMethod.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, expireSeconds * 1000);
        }
        if (logger.isDebugEnabled())
            logger.debug("http Request QueryString: " + httpMethod.getRequestLine().getUri());

        httpMethod.getURI();
        try {
            HttpResponse response = httpClient.execute(httpMethod);
            int status = response.getStatusLine().getStatusCode();
            String respBody = EntityUtils.toString(response.getEntity(), charSet);
            if (HttpServletResponse.SC_OK == status) {
                logger.debug("HTTP请求发送完毕. ");
                return respBody != null ? respBody.trim() : respBody;
            } else if (HttpServletResponse.SC_INTERNAL_SERVER_ERROR == status) {
                String errMsg = "调用【" + httpMethod.getURI() + "】远程服务时出现内部服务错误. " + ("".equals(respBody) ? "" : (". Response body: " + respBody));
                throw new BaseCheckedException(ERROR_INTERNAL_SERVER_ERROR, errMsg);
            } else if (HttpServletResponse.SC_NOT_FOUND == status) {
                String errMsg = "调用【" + httpMethod.getURI() + "】远程服务时出现找不到对应的服务. " + ("".equals(respBody) ? "" : (". Response body: " + respBody));
                throw new BaseCheckedException(ERROR_SERVICE_IS_NOT_FOUND, errMsg);
            } else if (HttpServletResponse.SC_FORBIDDEN == status) {
                String errMsg = "调用【" + httpMethod.getURI() + "】远程服务时出现请求受限（未经允许访问，如受限IP）. " + ("".equals(respBody) ? "" : (". Response body: " + respBody));
                throw new BaseCheckedException(ERROR_ILLEGAL_REQUEST, errMsg);
            } else {
                String errMsg = "调用【" + httpMethod.getURI() + "】远程服务时出现未处理的响应状态. Exception code: " + status + ("".equals(respBody) ? "" : (". Response body: " + respBody));
                throw new BaseCheckedException(ERROR_SERVICE_UNAVAILABLE, errMsg);
            }
        } catch (ClientProtocolException e) {
            String errMsg = "调用【" + httpMethod.getURI() + "】远程服务时发生ClientProtocolException，异常信息: " + e.getMessage();
            throw new BaseCheckedException(ERROR_SERVICE_UNAVAILABLE, errMsg);
        } catch (IOException e) {
            String errMsg = "调用【" + httpMethod.getURI() + "】远程服务时发生IOException，异常信息: " + e.getMessage();
            throw new BaseCheckedException(ERROR_SERVICE_UNAVAILABLE, errMsg);
        }
    }

    /**
     * 从HttpServletRequest中获取远程IP
     * 
     * @param request
     * @return
     */
    public static String getRemoteIP(HttpServletRequest request) {
        final String UNKNOWN = "unknown";
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtil.isEmpty(ip) || ip.startsWith(UNKNOWN)) {
            ip = request.getHeader("Proxy-Client-IP");
        } else {
            ip = ip.split(",")[0];
        }
        if (StringUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取服务器的主机名称
     * 
     * @return
     */
    public static String getHostName() {
        String hostName = System.getenv("HOSTNAME");
        if (StringUtil.isEmpty(hostName)) {
            try {
                hostName = InetAddress.getLocalHost().getHostName();
            } catch (Exception e) {
                logger.warn(e);
            }
        }
        return hostName;
    }

    /**
     * 从网络中下载图片到指定地址
     * 
     * @author yzq
     * @param url
     * @param path 将下载图片下载后存放的路径
     */
    public static boolean downloadImage(String url, String path) {

        if (!new File(path).exists()) {

            OutputStream os = null;

            logger.info("start download image:" + path);
            long start = System.currentTimeMillis();
            // 下载图片的信息
            byte[] image = getImageFromNetWork(HTTP_CLIENT, url);
            if (null == image) {
                logger.info("get the image fail to locale !Image path:" + path);
                return false;
            }

            try {
                // 通过这个方法，当文件所在的父目录不存在的时候，将自动创建其所有的父目录
                os = FileUtils.openOutputStream(new File(path));
                IOUtils.write(image, os);
                logger.info("end download image, all time:" + (System.currentTimeMillis() - start) + "ms");
                return true;
            } catch (IOException e) {
                logger.warn("write image error!!path:" + path, e);
                return false;
            } finally {
                // 释放所有的链接资源，一般在所有的请求处理完成之后，才需要释放
                // httpclient.getConnectionManager().shutdown();
                IOUtils.closeQuietly(os);
            }
        } else {
            logger.info("file is already exist!! :" + path);
            return true;
        }
    }

    /**
     * 从网络中抓取图片
     * 
     * @author yzq
     * @param httpClient
     * @param url
     * @return byte[]
     * @throws IOException
     */
    public static byte[] getImageFromNetWork(HttpClient httpclient, String url) {

        InputStream is = null;
        HttpGet get = null;
        try {
            // 利用HTTP GET向服务器发起请求
            get = new HttpGet(url);
            get.setHeader("Referer", url);
            // 获得服务器响应的的所有信息
            HttpResponse response = httpclient.execute(get);
            // 获得服务器响应回来的消息体（不包括HTTP HEAD）
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                return IOUtils.toByteArray(is);
            }
        } catch (Exception e) {
            logger.warn("getImageFromNetWork fail!!url:" + url, e);
        } finally {
            get.abort();
            IOUtils.closeQuietly(is);
        }
        return null;
    }

    public static void main(String[] args) {

        String[] imgs = { "http://xyq.pic.17173.com/uploads/2013/07/03/1372836708_2624852_m.jpg","http://mat1.gtimg.com/pinglun/images/20110524/logo_luntan.png"
        };

        for (int i = 0; i < imgs.length; i++) {

            String temp = imgs[i];

            String imgName = temp.substring(temp.lastIndexOf("/"));

            downloadImage(imgs[i], "G:/aa/bb/cc/dd/ee/" + imgName);
        }

        // downloadImage("http://imgsrc.baidu.com/forum/pic/item/38b49113e0b964e4f6039e4f.jpg",
        // "G:/ddd.jpg");

    }

}
